#coding=utf-8
__author__ = 'Meteor'
import json,jsonpath
from tools.loggingModule import logger
import re

class AstResp(object):
    # 接收要断言的内容
    def __init__(self,asst_info,response):
        # {'status_code': 200, '$.message[0]': '登录成功'}
        self.info = asst_info
        logger.info('断言信息：%s' %asst_info)
        self.response = response
        logger.info('响应报文体：%s' %response.text)

    def asstiong(self):
        flag = None
        for key,value in self.info.items():
            if key  == "status_code":
                flag = self.assert_status_code(value)
            elif key.startswith('$') or key.startswith('@') or key.startswith('.') or key.startswith('['):
                flag =self.asst_json_path(key,value)
            else:
                flag = self.re_asser(key,value)
        return flag



    def rest_text(self):
        return json.loads(self.response.text)


    # 断言响应的状态码
    def assert_status_code(self,code):
        return self.response.status_code == code

    # json断言
    def asst_json_path(self,path,excet):
        if not jsonpath.jsonpath(self.rest_text(),path):
            logger.error('assert failed ,%s not geted' %path)
            return False
        return jsonpath.jsonpath(self.rest_text(),path)[0] == excet

    # 正则断言
    def re_asser(self,path,excet):
        if re.findall(path,self.response.text):
            return re.findall(path,self.response.text)[0] == excet

# ast1 = AstResp({'status_code': 200, '$.message[0]': '登录成功'})
# ast1.asstiong()